package com.ymk.base.service;

import com.alibaba.fastjson.JSON;
import com.ymk.base.utlis.Aes;
import com.ymk.base.utlis.OSSCreateFolder;
import com.ymk.base.utlis.ParamsBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@Component
public class OssService{

    @Autowired
    private OSSCreateFolder ossCreateFolder;


    public String ossUpload(MultipartFile srcFile) throws IOException {
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild();
        String type = getcontentType(srcFile.getOriginalFilename());
        String substring = Objects.requireNonNull(srcFile.getOriginalFilename()).substring(srcFile.getOriginalFilename().lastIndexOf("."));
        String name = Aes.getMD5(srcFile.getName(),Aes.creatSalt());
        String upload = ossCreateFolder.upload(name + substring, type, srcFile.getBytes());
        paramsBuilder.addParam("url",upload)
                .addParam("name",srcFile.getOriginalFilename());
        return JSON.toJSONString(paramsBuilder.build());
    }

    public static String getcontentType(String FilenameExtension) {
        if (StringUtils.containsIgnoreCase(FilenameExtension,".bmp")) {
            return "image/bmp";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".gif")) {
            return "image/gif";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".jpeg") ||
                StringUtils.containsIgnoreCase(FilenameExtension,".jpg") ||
                StringUtils.containsIgnoreCase(FilenameExtension,".png")) {
            return "image/jpg";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".mp4") ||
                StringUtils.containsIgnoreCase(FilenameExtension,".MP4")) {
            return "video/mp4";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".zip")) {
            return "application/zip";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".html")) {
            return "text/html";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".txt")) {
            return "text/plain";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".vsd")) {
            return "application/vnd.visio";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (StringUtils.containsIgnoreCase(FilenameExtension,".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }
}
